//定义全局变量
var useName;
var couponArr = [];
var hadUsedArr = [];
var token = selectByKey("like_token");
//模板
function ajaxHtml(data,typeClass){
    var mainHtml = document.querySelector("main");
    var html = "";
    //重新排序
    for(var i = 0; i < data.length; i++){
        for(var j = i; j < data.length; j++){
            if(Math.floor(data[j].price) < Math.floor(data[i].price)){
                var k = data[j];
                data[j] = data[i];
                data[i] = k;
            }
        }
    }
    var nowdate = new Date().getTime();
    for(var k in data){
        var useNameTemp = useName;
        var typeClassTemp = typeClass;
        if(data[k].pivot){
            if(data[k].pivot.is_used != 0){
                useNameTemp = "已使用";
                typeClassTemp = "usedClass";
            }
        }
        if(couponArr.indexOf(data[k].id) != -1){
            useNameTemp = "立即使用";
            typeClassTemp = "use_now";
        }
        if(hadUsedArr.indexOf(data[k].id) != -1){
            useNameTemp = "已使用";
            typeClassTemp = "usedClass";
        }
        var pretime = data[k].end_time.replace(/\-/g,"/");
        pretime = Date.parse(pretime);
        if(nowdate>pretime){
            useNameTemp = "已过期";
            typeClassTemp = "usedClass";
        }
        if(data[k].limit>0){
            var htmlMode = document.getElementById("manjianMode").innerHTML;
        }else{
            var htmlMode = document.getElementById("diyongMode").innerHTML;
        }
        var type = data[k].title;
        if(data[k].price < 1000){
            var className = "hundred_num";
        }else{
            var className = "thunsand_num";
        }
        switch (parseInt(data[k].is_css)){
            case 0:
                var listName = "default";
                break;
            case 1:
                var listName = "activity";
        }
        htmlMode = htmlMode.replace(/\{\{coupon_id\}\}/, data[k].id);
        htmlMode = htmlMode.replace(/\{\{className\}\}/, className);
        htmlMode = htmlMode.replace(/\{\{listName\}\}/, listName);
        htmlMode = htmlMode.replace(/\{\{diyongPrice\}\}/, Math.floor(data[k].price));
        htmlMode = htmlMode.replace(/\{\{limitPrice\}\}/, data[k].limit);
        htmlMode = htmlMode.replace(/\{\{type\}\}/, type);
        htmlMode = htmlMode.replace(/\{\{date\}\}/, data[k].end_time.split(" ")[0]);
        htmlMode = htmlMode.replace(/\{\{useName\}\}/, useNameTemp);
        htmlMode = htmlMode.replace(/\{\{dataType\}\}/, data[k].type);
        htmlMode = htmlMode.replace(/\{\{endtime\}\}/, data[k].collection_time);
        if(data[k].is_css == 1){
            htmlMode = htmlMode.replace(/\{\{typeClass\}\}/, "get_diyong "+typeClassTemp);
        }else{
            htmlMode = htmlMode.replace(/\{\{typeClass\}\}/, typeClassTemp);
        }
        html += htmlMode;
    }
    mainHtml.innerHTML = html;
}
//提示信息
function infoMessage(message,status){
    var info = document.querySelector(".info");
    var infomsg = info.querySelector("p");
    info.style.display = "block";
    infomsg.innerHTML = message;
    info.style.opacity = 1;
    setTimeout(function () {
        info.style.opacity = 0;
    }, 1500);
    if(status == 1){
        setTimeout(function () {
            info.style.display = "none";
            location.reload();
        }, 1500);
    }
}

function getNowFormatDate() {
    var date = new Date();
    var seperator1 = "-";
    var seperator2 = ":";
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    var second = date.getSeconds();
    if(second < 10){
        second = "0" + second;
    }
    var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
        + " " + date.getHours() + seperator2 + date.getMinutes()
        + seperator2 + second;
    return currentdate;
}

//设置过期时间
function getTimeCha(time){
    var nowDate = getNowFormatDate();
    console.log(time);
    console.log(nowDate);
    return time > nowDate;
}
//领取优惠券
function getCoupon(){
    var useNow = document.getElementsByClassName("get_manjian");
    var em = document.querySelector("header em");
    //ajax请求
    function ajaxReq(couponId,dom){
        $.ajax({
            url: pathName + "/api/v1/member/receiveCoupon",
            type: "post",
            headers: {
                "Accept": "application/json",
                "Authorization": "Bearer " + token
            },
            data: {
                "couponId": couponId
            },
            success: function (res) {
                console.log(res);
                if (res.status_code == 200) {
                    dom.setAttribute("class", "use_now");
                    dom.innerHTML = "立即使用";
                    em.innerHTML = "我的优惠券(" + res.success.coupon_count + ")";
                    useCoupon();
                    //console.log(info)
                    infoMessage("领取成功",0);
                } else if (res.status_code == 20031) {
                    infoMessage("领取时间已过",1);
                }
            }
        })
    }
    for(var i = 0; i < useNow.length; i++){
        Tap(useNow[i],function(e,dom){
            var couponId = dom.parentNode.parentNode.getAttribute("data-coupon_id");
            var info = document.querySelector(".info");
            var typeClass = dom.parentNode.parentNode.getAttribute("data-type");
            if(token){
                if(typeClass == 2){
                    var collectTime = dom.parentNode.parentNode.getAttribute("data-endtime");
                    var timeCha = getTimeCha(collectTime);
                    if(timeCha) {
                        ajaxReq(couponId,dom);
                    }else {
                        infoMessage("领取时间已过",1);
                    }
                }else{
                    ajaxReq(couponId,dom);
                }
            }else{
                toEnter();
            }
        });
    }
}
//使用优惠券
function useCoupon(){
    var useCoupons = document.getElementsByClassName("use_now");
    for(var j = 0; j < useCoupons.length; j++){
        Tap(useCoupons[j],function(){
            window.location.href = "../online.html";
        });
    }
}
//登录弹框
function toEnter(){
    var markT = document.getElementsByClassName("markT")[0];
    var sureT = document.getElementById("sureT");
    var cancleT = document.getElementById("cancleT");
    markT.style.display = "block";
    Tap(sureT,function(){
        window.location.href = "enter.html";
    });
    Tap(cancleT,function(){
        markT.style.display = "none";
    });
}
//返回部分
function back(){
    var hash = location.hash;
    var back = document.querySelector("header a");
    Tap(back,function(){
        switch (hash){
            case "#getCoupon":
                location.href = "../../index.html";
                break;
            case "#personCenter":
                location.href = "individual.html";
                break;
            default :
                break;
        }
    })
}
window.onload = function(){
    var headerName = document.querySelector("header p");
    var getAll = document.querySelector("header em");
    var hash = location.hash;
    useCoupon();
    back();
    switch (hash){
        case "#getCoupon":
            useName = "立即领取";
            headerName.innerHTML = "领券中心";
            if(token){
                //ajax请求优惠券数量
                $.ajax({
                    url:pathName+"/api/v1/member/myCoupons",
                    type:"get",
                    headers:{
                        "Accept":"application/json",
                        "Authorization":"Bearer "+token
                    },
                    success:function(res){
                        var num = 0;
                        for(var k in res.data){
                            num++;
                        }
                        getAll.innerHTML = "我的优惠券("+num+")";
                    }
                })
            }else{
                getAll.innerHTML = "我的优惠券(0)";
            }
            $.ajax({
                url:pathName+"/api/v1/coupon",
                type:"get",
                success:function(response){
                    console.log(response);
                    if(token){
                        $.ajax({
                            url:pathName+"/api/v1/member/myCoupons",
                            type:"get",
                            headers:{
                                "Accept":"application/json",
                                "Authorization":"Bearer "+token
                            },
                            success:function(res){
                                console.log(res);
                                for(var k in res.data){
                                    if(res.data[k].pivot){
                                        if(res.data[k].pivot.is_used != 0){
                                            hadUsedArr.push(res.data[k].id);
                                        }else{
                                            couponArr.push(res.data[k].id);
                                        }
                                    }else{
                                        couponArr.push(res.data[k].id);
                                    }

                                }
                                ajaxHtml(response.data,"get_manjian");
                                getCoupon();
                                useCoupon();
                            }

                        })
                    }else{
                        ajaxHtml(response.data,"get_manjian");
                        getCoupon();
                        useCoupon();
                    }

                }
            });
            Tap(getAll,function(e,dom){
                if(token){
                    if(dom.innerHTML != "规则"){
                        window.location.href = "coupon.html#personCenter";
                        getAll.innerHTML = "规则";
                        document.querySelector("header p").innerHTML = "我的优惠券";
                        var info = document.querySelector(".ruleMark");
                        Tap(getAll,function(){
                            info.style.display = "block";
                        });
                        Tap(info,function(){
                            info.style.display = "none";
                        });
                        $.ajax({
                            url:pathName+"/api/v1/member/myCoupons",
                            type:"get",
                            headers:{
                                "Accept":"application/json",
                                "Authorization":"Bearer "+token
                            },
                            success:function(res){
                                ajaxHtml(res.data,"use_now");
                                getCoupon();
                                useCoupon();
                            }

                        })
                    }else{

                    }

                }else{
                    var mark = document.querySelector(".markT");
                    var sure = mark.querySelector("#sureT");
                    var cancel = mark.querySelector("#cancleT");
                    mark.style.display = "block";
                    Tap(sure,function(){
                        window.location.href = "enter.html";
                    });
                    Tap(cancel,function(){
                        mark.style.display = "none";
                    });
                }
            });
            break;
        case "#personCenter":
            useName = "立即使用";
            headerName.innerHTML = "我的优惠券";
            getAll.innerHTML = "规则";

            $.ajax({
                url:pathName+"/api/v1/member/myCoupons",
                type:"get",
                headers:{
                    "Accept":"application/json",
                    "Authorization":"Bearer "+token
                },
                success:function(res){
                    ajaxHtml(res.data,"use_now");
                    getCoupon();
                    useCoupon();
                }
            })
            var info = document.querySelector(".ruleMark");
            Tap(getAll,function(){
                info.style.display = "block";
            });
            Tap(info,function(){
                info.style.display = "none";
            });
            break;
        default :
            break;
    }

}